package com.pdd.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pdd.mall.dto.StatisticsDataDTO;
import com.pdd.mall.dto.UserAnalysisDTO;
import com.pdd.mall.entity.Product;
import com.pdd.mall.mapper.OrderMapper;
import com.pdd.mall.mapper.ProductMapper;
import com.pdd.mall.mapper.UserMapper;
import com.pdd.mall.service.StatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 统计服务实现类
 */
@Service
public class StatisticsServiceImpl implements StatisticsService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public StatisticsDataDTO getMerchantStatistics(Long merchantId) {
        StatisticsDataDTO statisticsData = new StatisticsDataDTO();

        // 获取商家的商品总数
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        productQueryWrapper.eq("merchant_id", merchantId);
        Long count = productMapper.selectCount(productQueryWrapper);
        int totalProductCount = count != null ? count.intValue() : 0;
        statisticsData.setTotalProductCount(totalProductCount);

        // 模拟数据 - 实际项目中应该从数据库查询
        statisticsData.setTotalOrderCount(125);
        statisticsData.setTotalSales(new BigDecimal("15680.50"));

        // 近7天销售额
        List<Map<String, Object>> salesLast7Days = new ArrayList<>();
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");

        for (int i = 6; i >= 0; i--) {
            LocalDate date = today.minusDays(i);
            Map<String, Object> item = new HashMap<>();
            item.put("date", date.format(formatter));
            // 模拟数据
            item.put("sales", new BigDecimal(String.valueOf(Math.random() * 1000 + 500)).setScale(2, RoundingMode.HALF_UP));
            salesLast7Days.add(item);
        }
        statisticsData.setSalesLast7Days(salesLast7Days);

        // 各状态订单数量
        Map<String, Integer> orderStatusCount = new HashMap<>();
        orderStatusCount.put("待付款", 10);
        orderStatusCount.put("待发货", 25);
        orderStatusCount.put("待收货", 15);
        orderStatusCount.put("已完成", 70);
        orderStatusCount.put("已取消", 5);
        statisticsData.setOrderStatusCount(orderStatusCount);

        // 热销商品TOP5
        List<Map<String, Object>> hotProducts = new ArrayList<>();
        for (int i = 1; i <= 5; i++) {
            Map<String, Object> product = new HashMap<>();
            product.put("name", "热销商品" + i);
            product.put("sales", new BigDecimal(String.valueOf(Math.random() * 100 + 50)).setScale(0, RoundingMode.HALF_UP).intValue());
            hotProducts.add(product);
        }
        statisticsData.setHotProducts(hotProducts);

        return statisticsData;
    }

    @Override
    public StatisticsDataDTO getMerchantStatistics(Long merchantId, String timeRange, Integer pageNum, Integer pageSize) {
        // 先获取基本统计数据
        StatisticsDataDTO statisticsData = getMerchantStatistics(merchantId);

        // 生成销售明细数据（模拟数据，实际项目中应该从数据库查询）
        List<Map<String, Object>> allSalesDetail = generateSalesDetailData();

        // 设置总记录数
        statisticsData.setTotal(allSalesDetail.size());

        // 分页处理
        if (pageNum != null && pageSize != null) {
            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, allSalesDetail.size());

            if (startIndex < allSalesDetail.size()) {
                statisticsData.setSalesDetail(allSalesDetail.subList(startIndex, endIndex));
            } else {
                statisticsData.setSalesDetail(new ArrayList<>());
            }
        } else {
            statisticsData.setSalesDetail(allSalesDetail);
        }

        return statisticsData;
    }

    /**
     * 生成销售明细数据（模拟数据）
     */
    private List<Map<String, Object>> generateSalesDetailData() {
        List<Map<String, Object>> salesDetail = new ArrayList<>();
        LocalDate today = LocalDate.now();

        // 生成100条模拟数据
        for (int i = 0; i < 100; i++) {
            Map<String, Object> detail = new HashMap<>();
            LocalDate date = today.minusDays(i % 30); // 循环使用最近30天的日期

            detail.put("date", date.toString());
            detail.put("orderCount", 100 + (int)(Math.random() * 100));
            detail.put("salesAmount", 10000 + Math.random() * 10000);
            detail.put("productCount", 300 + (int)(Math.random() * 200));
            detail.put("customerCount", 90 + (int)(Math.random() * 60));

            // 计算平均客单价
            double salesAmount = (double) detail.get("salesAmount");
            int orderCount = (int) detail.get("orderCount");
            detail.put("avgOrderAmount", salesAmount / orderCount);

            salesDetail.add(detail);
        }

        return salesDetail;
    }

    @Override
    public UserAnalysisDTO getUserAnalysis(Long merchantId) {
        UserAnalysisDTO userAnalysis = new UserAnalysisDTO();

        // 模拟数据 - 实际项目中应该从数据库查询
        userAnalysis.setTotalUserCount(500);
        userAnalysis.setActiveUserCount(320);

        // 用户购买频次分布
        List<Map<String, Object>> purchaseFrequency = new ArrayList<>();
        Map<String, Object> item1 = new HashMap<>();
        item1.put("frequency", "1次");
        item1.put("count", 150);
        purchaseFrequency.add(item1);

        Map<String, Object> item2 = new HashMap<>();
        item2.put("frequency", "2-3次");
        item2.put("count", 100);
        purchaseFrequency.add(item2);

        Map<String, Object> item3 = new HashMap<>();
        item3.put("frequency", "4-10次");
        item3.put("count", 50);
        purchaseFrequency.add(item3);

        Map<String, Object> item4 = new HashMap<>();
        item4.put("frequency", "10次以上");
        item4.put("count", 20);
        purchaseFrequency.add(item4);

        userAnalysis.setPurchaseFrequency(purchaseFrequency);

        // 用户消费金额分布
        List<Map<String, Object>> consumptionDistribution = new ArrayList<>();
        Map<String, Object> consumption1 = new HashMap<>();
        consumption1.put("range", "0-100元");
        consumption1.put("count", 120);
        consumptionDistribution.add(consumption1);

        Map<String, Object> consumption2 = new HashMap<>();
        consumption2.put("range", "100-500元");
        consumption2.put("count", 150);
        consumptionDistribution.add(consumption2);

        Map<String, Object> consumption3 = new HashMap<>();
        consumption3.put("range", "500-1000元");
        consumption3.put("count", 80);
        consumptionDistribution.add(consumption3);

        Map<String, Object> consumption4 = new HashMap<>();
        consumption4.put("range", "1000元以上");
        consumption4.put("count", 50);
        consumptionDistribution.add(consumption4);

        userAnalysis.setConsumptionDistribution(consumptionDistribution);

        // 最近30天新增用户数
        List<Map<String, Object>> newUsersLast30Days = new ArrayList<>();
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");

        for (int i = 29; i >= 0; i--) {
            LocalDate date = today.minusDays(i);
            Map<String, Object> newUser = new HashMap<>();
            newUser.put("date", date.format(formatter));
            // 模拟数据
            newUser.put("count", (int) (Math.random() * 10 + 1));
            newUsersLast30Days.add(newUser);
        }
        userAnalysis.setNewUsersLast30Days(newUsersLast30Days);

        // 用户地域分布
        List<Map<String, Object>> userRegionDistribution = new ArrayList<>();
        Map<String, Object> region1 = new HashMap<>();
        region1.put("region", "广东");
        region1.put("count", 150);
        userRegionDistribution.add(region1);

        Map<String, Object> region2 = new HashMap<>();
        region2.put("region", "北京");
        region2.put("count", 100);
        userRegionDistribution.add(region2);

        Map<String, Object> region3 = new HashMap<>();
        region3.put("region", "上海");
        region3.put("count", 80);
        userRegionDistribution.add(region3);

        Map<String, Object> region4 = new HashMap<>();
        region4.put("region", "其他");
        region4.put("count", 170);
        userRegionDistribution.add(region4);

        userAnalysis.setUserRegionDistribution(userRegionDistribution);

        return userAnalysis;
    }
}
